package com.stropheware.droidDefense;

import com.stropheware.util.AccelerometerListener;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.graphics.drawable.shapes.RectShape;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;

public class GameBoardView extends SurfaceView implements 
OnTouchListener, SurfaceHolder.Callback {
	
	/*
	 * Tag used for LogCat
	 */
	private static final String TAG = "GameBoardView";
		
	private SurfaceHolder surfaceHolder;
	
	private AccelerometerListener aListener;
	
	public Context context;
	
	/*
	 * Reference to the thread which controls graphics/game control
	 *  Will communicate to View through use of Handlers
	 */
	private GameThread gameThread;
	
	public GameBoardView(Context context)  {
		super(context);
		this.context = context;
		setFocusable(true);
		setFocusableInTouchMode(true);
		this.setOnTouchListener(this);
		//this.setOnKeyListener(this);
		aListener = new AccelerometerListener(context, this);
	}
	
	@Override
	public void onSizeChanged(int w, int h, int oldw, int oldh) {
		Log.d(TAG, "width=" + w + " height=" + h);
		SurfaceHolder holder = getHolder();
		holder.addCallback(this);
		gameThread = new GameThread(holder, w, h, context);
		super.onSizeChanged(w, h, oldw, oldh);
	}
	
	public boolean onTouch(View view, MotionEvent event) {
		gameThread.onTouch(event);
		return true;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(event.getKeyCode() == KeyEvent.KEYCODE_ENTER){
			return gameThread.doOnKeyDown(keyCode, event);
		}
		else{
			return super.onKeyDown(keyCode, event);
		}
		
	}
		
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		
	}

	public void surfaceCreated(SurfaceHolder holder) {
		gameThread.setRunning(true);
		gameThread.start();
		aListener.start();
	}
	
	public void accelertatorShaken() {
		gameThread.acceleratorShaken();
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
        boolean retry = true;
        gameThread.setRunning(false);
        while (retry) {
            try {
                gameThread.join();
                aListener.stop();
                retry = false;
            } catch (InterruptedException e) {
            }
        }
    }

	public SurfaceHolder getSurfaceHolder() {
		return surfaceHolder;
	}


}
